<?php

namespace Modules\File\Http\Controllers\Api;


use Illuminate\Http\Request;
use Modules\Core\Http\Controllers\BaseController;
use Modules\File\Actions\ImgFetch;
use Modules\File\Actions\ImgUpload;

class FileController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function upload(Request $request)
    {
        // 网络抓取托管
        if($request->get('type') == 'fetch') {
            return $this->handleFetch($request);
        }

        $request->validate(['file' => 'required']);
        return $this->toResponse(
            ImgUpload::run($request->file('file'))
        );
    }

    /**
     * @param $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    protected function handleFetch($request)
    {
        $request->validate(['url' => 'required']);

        return $this->toResponse(
            ImgFetch::run($request->get('url'))
        );
    }


}
